"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/10/27
 */
import * as React from 'react'
import {commonProps, commonStyles} from "../../assets/styles/common";
import NavBackButton from "../../component/BackButton";

const NavigationBar = require('react-native-navbar').default;
import MyText from "../../component/MyText";
import Validator from "../../utils/Validator";
import {toastValidateError} from "../../utils/tools";
import {AuthComponent} from "../../interface/index";

const {createForm} = require('rc-form');
const {View} = require('react-native');
const {connect} = require('react-redux');
const {List, InputItem, Button} = require('antd-mobile');
const {KeyboardAwareScrollView} = require('react-native-keyboard-aware-scroll-view');


class ForgetPwdPage extends React.Component<AuthComponent, any> {
    timer: any;

    constructor(props: AuthComponent, context: any) {
        super(props, context);
        console.log('ForgetPwdPage constructor');
        this.state = {
            errors: {
                phone: false,
                password: false,
                verifycode: false,
                confirm: false,
            }
        }
    }

    componentWillUnmount(): void {
        clearInterval(this.timer);
        this.timer = null;
        this.props.dispatch({
            type: 'auth/clearTimer'
        })

    }


//验证器
    validator = ({field}, value, callBack) => {
        const errors = this.state.errors;
        errors[field] = true;
        if (field === 'phone') {
            if (value) {
                errors[field] = !Validator.validator(value.replace(/ /g, ''), Validator.phoneReg);
            }
            if (errors[field]) {
                callBack('手机号不合法');
            } else {
                callBack();
            }
            this.setState({errors})
        } else if (field === 'password' || field === 'confirm') {
            errors[field] = !(value && value.length >= 6);
            if (errors[field]) {
                callBack('密码不合法');
            } else {
                callBack();
            }
            this.setState({errors})
        } else if (field === 'verifycode') {
            errors[field] = !Validator.validator(value, Validator.numberReg);
            if (errors[field]) {
                callBack('验证码不合法');
            } else {
                callBack();
            }
            this.setState({errors})
        }
    };


    /**
     * 注册
     */
    onSubmit = () => {
        const {dispatch, form} = this.props;

        // {validator: this.validator.bind(this)}
        form.validateFields((error, value) => {
            if (!error) {
                let {phone, password, verifycode, confirm} = form.getFieldsValue();
                phone = phone.replace(/ /g, '');
                dispatch({
                    type: 'auth/changePassword',
                    payload: {phone, password, verifycode, confirm}
                });
            } else {
                toastValidateError(error);
            }
        });
    };
    //发送验证码
    onSendSms = () => {
        const {form, dispatch} = this.props;
        let {phone} = form.getFieldsValue();
        if (phone && Validator.validator(phone.replace(/ /g, ''), Validator.phoneReg)) {
            dispatch({
                type: 'auth/sendSms',
                payload: {phone: phone.replace(/ /g, '')}
            });
            this.starTimer();
        } else {
            toastValidateError(null, '手机号不合法');
        }
    };

    /**
     * 开启定时器
     */
    starTimer() {
        let {auth: {sending, coldDownTime,}, dispatch} = this.props;
        clearInterval(this.timer);
        if (sending) return;

        this.timer = setInterval(() => {
            if (coldDownTime > 0) {
                dispatch({
                    type: 'auth/save',
                    payload: {sendButtonText: `${coldDownTime--}s 后重试`, sending: true}
                })
            } else {
                clearInterval(this.timer);
                this.timer = null;
                dispatch({
                    type: 'auth/clearTimer',
                })
            }
        }, 900)

    }

    render() {
        const {getFieldProps} = this.props.form;
        const SenSmsBtn = ({title, loading = false, onPress}) => (
            <Button type="primary"
                    onClick={onPress}
                    title={title}
                    loading={this.props.auth.sending}
                    disabled={this.props.auth.sending}
                    style={[commonStyles.centerVH, {height: 26, width: 100}]}>
                <MyText style={{fontSize: 12, color: 'white'}}>{title}</MyText>
            </Button>);
        return (
            <View style={commonStyles.container}>
                <NavigationBar {...commonProps.navBar}
                               leftButton={<NavBackButton/>}
                               title={{title: '忘记密码', tintColor: '#fff'}}
                />
                <KeyboardAwareScrollView>
                    <List>
                        <InputItem  {...getFieldProps('phone', {
                            rules: [
                                {required: true, message: '手机号未填写'},
                                {validator: this.validator.bind(this)}
                            ]
                        })}
                                    placeholder="输入手机号"
                                    labelNumber={2}
                                    type="phone"
                                    clear
                                    error={this.state.errors.phone}
                                    extra={<SenSmsBtn title={this.props.auth.sendButtonText} onPress={this.onSendSms}/>}
                        />
                        <InputItem  {...getFieldProps('verifycode', {
                            rules: [
                                {required: true, message: '验证码未填写'},
                                {validator: this.validator.bind(this)}
                            ]
                        })}
                                    placeholder="输入验证码"
                                    labelNumber={2}
                                    type="number"
                                    error={this.state.errors.verifycode}
                                    clear

                        />
                        <InputItem  {...getFieldProps('password', {
                            rules: [
                                {required: true, message: '密码未填写'},
                                {validator: this.validator.bind(this)}
                            ]
                        })}
                                    placeholder="输入密码"
                                    labelNumber={2}
                                    type="password"
                                    error={this.state.errors.password}
                                    clear

                        />
                        <InputItem  {...getFieldProps('confirm', {
                            rules: [
                                {required: true, message: '确认密码'},
                                {validator: this.validator.bind(this)}
                            ]
                        })}
                                    placeholder="确认密码"
                                    labelNumber={2}
                                    type="password"
                                    error={this.state.errors.confirm}
                                    clear

                        />
                    </List>
                    <View style={{paddingVertical: 10, paddingHorizontal: 20}}>
                        <Button type="primary"
                                title="确认"
                                onClick={this.onSubmit.bind(this)}
                                style={{height: 40, marginBottom: 20}}>确认</Button>
                    </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }
}


const Wrapper = createForm()(ForgetPwdPage);
export default connect(
    ({auth}) => ({auth})
)(Wrapper);